<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useInitTable } from '@/hooks/useTable'
import {
  getUserListAPI,
  addUserAPI,
  updateUserAPI,
  updatePasswordAPI,
  deleteUserAPI
} from '@/api/user'

// 处理响应结果
const handleSuccess = (result) => {
  tableData.value = result.rows.map((item) => {
    item.btnLoading = false
    return item
  })
  total.value = result.count
}
// 列表 | 分页 | 搜索 | 多选 | 删除
const tableOptions = {
  params: {
    page: 1,
    pageSize: 10,
    username: null,
    nickname: null,
    status: 0,
    type: 0
  },
  getDataAPI: getUserListAPI,
  deleteAPI: deleteUserAPI,
  onSuccess: handleSuccess
}
const {
  params,
  tableData,
  tableLoading,
  total,
  multiSelection,
  getData,
  handleSearch,
  handleSelectionChange,
  handleBatchDelete,
  handleDelete,
  handleIndex
} = useInitTable(tableOptions)

// 添加 | 修改
const avatarRef = ref(null)
const addForm = ref({})
const formRef = ref(null)
const dialogVisible = ref(false)
const btnLoading = ref(false)
const addFormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  password: [{ required: true, message: '输入密码', trigger: 'blur' }]
}
// 打开弹窗
const handleOpenDialog = (row) => {
  addForm.value = row
  formRef.value?.resetFields()
  dialogVisible.value = true
}
// 添加
const handleAdd = () => {
  isUpdatePassword.value = false
  avatarRef.value?.reset()
  handleOpenDialog({ username: '', password: '', avatar: '-1' })
}
// 修改
const handleEdit = (row) => {
  isUpdatePassword.value = false
  handleOpenDialog({ id: row.id, nickname: row.nickname, avatar: row.avatar, status: row.status })
}
const isAdd = computed(() => !Boolean(addForm.value.id))
// 提交数据
const handleAddOrUpdate = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    btnLoading.value = true
    try {
      // 修改密码
      if (isUpdatePassword.value) {
        await updatePasswordAPI(addForm.value)
        ElMessage.success('修改成功')
        dialogVisible.value = false
        getData()
        return
      }
      addForm.value.avatar = await avatarRef.value.getImgUrl()
      // 判断是添加或修改
      if (isAdd.value) {
        await addUserAPI(addForm.value)
      } else {
        await updateUserAPI(addForm.value)
      }
      ElMessage.success((isAdd.value ? '添加' : '编辑') + '成功')
      dialogVisible.value = false
      getData()
    } finally {
      btnLoading.value = false
    }
  })
}

// 修改密码
const isUpdatePassword = ref(false)
const handleUpdatePassword = (row) => {
  isUpdatePassword.value = true
  handleOpenDialog({ id: row.id, password: '' })
}

const dialogTitle = computed(() => {
  if (isUpdatePassword.value) {
    return '修改密码'
  } else if (isAdd.value) {
    return '添加用户'
  } else {
    return '编辑用户'
  }
})
</script>

<template>
  <layout-card>
    <!-- 搜索区域 -->
    <el-form class="search-container" :model="params" inline>
      <el-form-item label="用户名:">
        <el-input v-model="params.username" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="昵称:">
        <el-input v-model="params.nickname" placeholder="请输入昵称" clearable />
      </el-form-item>
      <el-form-item label="类型:">
        <el-select class="select" v-model="params.type" placeholder="选择用户类型">
          <el-option label="全部" :value="0" />
          <el-option label="用户" :value="1" />
          <el-option label="游客" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态:">
        <el-select class="select" v-model="params.status" placeholder="选择用户状态">
          <el-option label="全部" :value="0" />
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item class="search-btn">
        <el-button type="primary" @click="handleSearch" icon="Search">搜索</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作区域 -->
    <div class="handle-container">
      <el-button v-permission="'user:list:register'" type="primary" @click="handleAdd"
        >添加用户</el-button
      >
      <el-button v-permission="'user:list:deleteUser'" @click="handleBatchDelete"
        >批量删除</el-button
      >
    </div>
    <!-- 表格区域 -->
    <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="55" :index="handleIndex" />
      <el-table-column label="用户名" prop="username" show-overflow-tooltip />
      <el-table-column label="昵称" prop="nickname" show-overflow-tooltip />
      <el-table-column label="头像">
        <template #default="{ row }">
          <zy-avatar :url="row.avatar" width="40px" height="40px" radius="3px" preview-teleported />
        </template>
      </el-table-column>
      <el-table-column label="类型">
        <template #default="{ row }">
          <el-tag :type="row.type === 1 ? 'success' : 'primary'" effect="plain">{{
            row.type === 1 ? '用户' : '游客'
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">{{
            row.status === 1 ? '正常' : '禁用'
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="ip" prop="ip" />
      <el-table-column label="注册时间" prop="created_time" width="180" />
      <el-table-column label="操作" fixed="right" width="180">
        <template #default="{ row }">
          <el-button
            v-permission="'user:list:updateUserAdmin'"
            type="primary"
            link
            @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            v-permission="'user:list:updateUserPassword'"
            type="primary"
            link
            :disabled="row.type === 2"
            @click="handleUpdatePassword(row)"
            >修改密码</el-button
          >
          <el-popconfirm title="确定要删除此用户吗？" @confirm="handleDelete(row)">
            <template #reference>
              <el-button
                v-permission="'user:list:deleteUser'"
                :loading="row.btnLoading"
                type="primary"
                link
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="params.page"
        v-model:page-size="params.pageSize"
        :page-sizes="[10, 50, 80, 100]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSearch"
        @current-change="getData"
      />
    </div>
    <!-- 弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" align-center width="420px">
      <!-- 表单 -->
      <el-form
        class="dialog-form"
        ref="formRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="65px"
      >
        <!-- 修改密码 -->
        <template v-if="isUpdatePassword">
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addForm.password" show-password />
          </el-form-item>
        </template>
        <template v-else>
          <!-- 添加 -->
          <template v-if="isAdd">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password" type="password" show-password />
            </el-form-item>
          </template>
          <!-- 编辑 -->
          <template v-else>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="addForm.nickname" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="addForm.status"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="正常"
                inactive-text="禁用"
                :active-value="1"
                :inactive-value="2"
              />
            </el-form-item>
          </template>
          <el-form-item label="头像">
            <zy-upload-avatar ref="avatarRef" :url="addForm.avatar" />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="btnLoading" type="primary" @click="handleAddOrUpdate">确 定</el-button>
      </template>
    </el-dialog>
  </layout-card>
</template>

<style lang="scss" scoped>
.search-container {
  .el-form-item {
    margin-bottom: 10px;
    .select {
      width: 130px;
    }
    &.search-btn {
      margin-right: 0;
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: end;
}
</style>
